package inits

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"time"
	"zg3yk/config"
	"zg3yk/global"
	"zg3yk/interface/models"
)

var err error

func MysqlInit() {
	Data := config.Data.Mysql

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", Data.User, Data.Password, Data.Host, Data.Port, Data.Database)
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})

	if err != nil {
		panic(err)
	} else {
		fmt.Println("数据库连接成功")
	}

	err = global.DB.AutoMigrate(&models.Users{}, &models.Rooms{}, models.Danmus{}, &models.Videos{})
	if err != nil {
		panic(err)
	} else {
		fmt.Println("迁移成功")
	}
	sqlDB, _ := global.DB.DB()

	// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
	sqlDB.SetMaxIdleConns(15)
	// SetMaxOpenConns sets the maximum number of open connections to the database.
	sqlDB.SetMaxOpenConns(150)
	// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
	sqlDB.SetConnMaxLifetime(time.Hour * 10)
	fmt.Println(sqlDB)
}
